<?php


namespace Module\DyAi\Api\Controller;

use Illuminate\Routing\Controller;
use ModStart\Core\Dao\ModelUtil;
use ModStart\Core\Input\InputPackage;
use ModStart\Core\Input\Response;
use Module\DyAi\Model\DownContent;
use Module\DyAi\Model\DyAiKeysugg;
use Module\DyAi\Model\DyAiCategory;
use DOMDocument;
use GuzzleHttp\Client;

/**
 * @Api 当游网ai助手
 */
class DownContentController extends Controller
{

    /**
     * @Api 分页列表
     * @ApiBodyParam categoryId int 分类ID
     * @ApiBodyParam keywords string 关键词
     * @ApiResponseData {
     *  "total": 1,
     *  "page" : 1,
     *  "pageSize": 10,
     *  "records": [
     *      {
     *        "id":1,
     *        "categoryId":1,
     *        "title":"标题",
     *        "summary":"摘要",
     *        "content":"内容"
     *      }
     *  ]
     * }
     */
    public function paginate()
    {
        $input = InputPackage::buildFromInput();
        $page = $input->getPage();
        $pageSize = $input->getPageSize();

        $query = DownContent::query();
        $categoryId = $input->getInteger('categoryId');
        if ($categoryId) {
            $query = $query->where('categoryId', $categoryId);
        }
        $keywords = $input->getTrimString('keywords');
        if ($keywords) {
            $query = $query->where('title', 'like', '%' . $keywords . '%');
        }
        $query = $query->orderBy('id', 'desc');
        $result = $query->paginate($pageSize, ['*'], 'page', $page)->toArray();
        $paginateData = [
            'records' => $result['data'],
            'total' => $result['total'],
        ];

        return Response::generateSuccessData([
            'page' => $page,
            'pageSize' => $pageSize,
            'total' => $paginateData['total'],
            'records' => $paginateData['records'],
        ]);
    }


    /**
     * @Api 获取详情
     * @ApiBodyParam id int ID
     * @ApiResponseData {
     *   "id":1,
     *   "categoryId":1,
     *   "title":"标题",
     *   "summary":"摘要",
     *   "content":"内容"
     * }
     */
    public function get()
    {
        $input = InputPackage::buildFromInput();
        $id = $input->getInteger('id');
        $record = ModelUtil::get('dy_ai', $id);
        $record['_category'] = DyAiCategory::recordGet($record['categoryId']);
        return Response::generateSuccessData([
            'record' => $record,
            'categories' => DyAiCategory::categoryTree(),
            'latestRecords' => DownContent::recordsLatest(),
        ]);
    }

	function stripHTMLTags($html) {
		$dom = new DOMDocument();
		$html = preg_replace('/<trackartist\b[^>]*>(.*?)<\/trackartist>/si', '<span class="trackartist">$1</span>', $html);  
		$dom->loadHTML('<?xml encoding="UTF-8">' . $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); 
		$dom->preserveWhiteSpace = false;
		$text = '';
		foreach ($dom->childNodes as $child) {
			$text .= $dom->saveHTML($child);
		}
		// 使用 strip_tags 来去除剩余的 HTML 标签
		$text = strip_tags($text);
		return trim($text);
	}
	
    /**
     * @Api 查询
     */
    public function first()
    {
        $result = DownContent::whereNull('ai_json')->first();//
		$url = 'http://gs2.3h3.com:8082/DyV2.aspx?api=GetAIToken';
		$client = new Client;
        $response = $client->post($url,['form_params'=>['id'=>$result['ai_role_id'],'did'=>6,'get_content'=>1]]);
		$json = json_decode($response->getBody(),true);
		//$result['json'] = $json;
		$url = 'http://gs2.3h3.com:8082/DyV2.aspx?api=GetAIContent';
		$result['html_content'] = $result['content'];
		$text = $result['html_content'];//$this->stripHTMLTags($result['html_content']);
		$response = $client->post($url, [  
						'form_params' => [ // 使用 form_params 而不是 content，它会自动 URL 编码  
							'content' => $text,  
							'SubmitFormat' => 1,  
						],  
						'headers' => [  
							'Content-Type' => 'application/x-www-form-urlencoded', // 明确设置 Content-Type  
						],  
					]);
		$json2 = json_decode($response->getBody(),true);
		$text_json = $json2['datas']?$json2['datas']:$text;
		$result['content'] = $text_json;//$json['datas'][0]['token_json']['GPStartStr'].
        return Response::generateSuccessData($result);
    }

    /**
     * @Api 保存
     */
    public function save()
    {
        $input = InputPackage::buildFromInput();
        $id = $input->getInteger('id');
        $down_id = $input->getInteger('down_id');
        $categoryId = $input->getInteger('categoryId');
        $catid = $input->getInteger('catid');
        $title = $input->getTrimString('title');
        $softname = $input->getTrimString('softname');
        $cover = $input->getTrimString('cover');
        $summary = $input->getTrimString('summary');
        $content = $input->getTrimString('content');
        $ai_json = $input->getTrimString('ai_json');
        if(!$id){//新增
			$downcontent = DownContent::where(['down_id' => $down_id,'categoryId'=>$categoryId])->first();
            if(!$downcontent){
				$arr = ['categoryId'=>$categoryId,'catid' => $catid,'down_id'=>$down_id,'title'=>$title,'softname'=>$softname,'cover'=>$cover,'summary'=>$summary,'content'=>$content];
				$result = ModelUtil::insert('down_content', $arr);
			}
		}else{//修改
            $downcontent = DownContent::where(['id' => $id])->first();
            $downcontent->ai_json = $ai_json;
            if(trim($ai_json)!='')$result = $downcontent->save();
		}
        return Response::generateSuccessData($result);
    }
	
	public function insert_callback(){//插入凤鑫那边导入的数据
		$list = ModelUtil::model('callback')->orderby('id','asc')->get()->toArray();
		foreach($list as $r){
			$content = json_decode($r['content'],true);
			$id = str_replace('http://'.$_SERVER['HTTP_HOST'].'/api/ai/callback_content?id=','',$content['CallBackUrl']);
			$dc = DownContent::whereNull('ai_json')->whereIn('id',[$id])->first();
			if($dc){
				$dc->ai_json = str_replace('','',$r['result_content']);
				$dc->save();
				var_dump($id);
			}
		}
		return Response::generateSuccess();
	}

    //同步软件的ai_json
    public function sync_down_ai_json()
    {
        $all_dep = DyAiCategory::all();
        $limit = 10;
        $site_urls = [1=>'www.downxia.cn',2=>'www.3h3.com',3=>'www.87g.com',4=>'www.downxing.com'];
        $client = new Client;
        try{
            foreach($all_dep as $a_i=>$dep) {
                $downs = DownContent::whereNotNull('ai_json')->where('categoryId',$dep['id'])->where('is_send_read',0)->limit($limit)->get(['id','down_id','title','softname','ai_json'])->toArray();
                $url = 'http://'.$site_urls[$dep['id']].'/index.php?m=content&c=api&a=save_down_ai_json';
                $response = $client->post($url, [
                    'json' => $downs,
                    'headers' => [
                        'Content-Type' => 'application/json', // 明确设置 Content-Type
                    ],
                ]);
                $json = json_decode($response->getBody(), true);
                $down_ids = [];
                foreach ($downs as $r){
                    $down_ids[] = $r['id'];
                }
                DownContent::whereIn('id',$down_ids)->update(['is_send_read'=>1]);
            }
        }catch(\Exception $e){
            return Response::generateError($e->getMessage(). ' -> ' . $e->getTraceAsString());
        }
        return Response::generateSuccess();
    }
	
	//根据软件名获取软件标签
	public function get_tag_by_softname(){
		$input = InputPackage::buildFromInput();
		$softname = $input->getTrimString('softname');
		$results = DownContent::whereNotNull('ai_json')->where('softname', '=', $softname)->get()->toArray();
		if(count($results) == 0){header("HTTP/1.0 404 Not Found");exit;}
		$ai_json = json_decode($results[0]['ai_json'],true);
		$filterwords = modstart_config('DyAi_filterword','')?explode(PHP_EOL,modstart_config('DyAi_filterword','')):[];
        $nowords = modstart_config('DyAi_noword','')?explode(PHP_EOL,modstart_config('DyAi_noword','')):[];
        $keys = $ai_json['comprehensive_keywords'];
		$ai_biaoqian = [];
        foreach($keys as $k=>$key){
			$istrue = false;
			foreach($filterwords as $fk=>$word){
				if (substr_compare($key, $word, -strlen($word)) === 0) {
					$istrue = true;
					break;
				}
			}
			foreach($nowords as $fk=>$word){
				if (substr_compare($key, $word, -strlen($word)) === 0) {
					$istrue = false;
					break;
				}
			}
			if($istrue && strstr($key,$results[0]['softname']) == false){
				$search_keyword = mb_substr($key, 0, -1);
				$ai_biaoqian[] = $key;
			}
		}
		$json = ['ai_biaoqian'=>$ai_biaoqian,'ai_json'=>$ai_json];
		return Response::generateSuccessData($json);
	}
	
    public function keysugg_softsize()//同步下拉词匹配到的软件数量
    {
		$pagesize = 200;
		$today = date('Y-m-d');
		$keys = DyAiKeysugg::whereBetween('updated_at', [date('Y-m-d',strtotime('-100 year')),date('Y-m-d',strtotime('2024-09-20'))])->whereBetween('soft_size',[0,0])->take($pagesize)->get(['id','keyword','search_keyword'])->toArray();//whereIn('id',[429824])->
		if(count($keys)>0){
		foreach ($keys as $k=>$sugg){
			$count = DownContent::whereRaw("ai_json LIKE ?", ["%\"{$sugg['keyword']}\"%"])->count();//where('ai_json', 'like', '%' . $sugg['keyword'] . '%')
			DyAiKeysugg::where('id', $sugg['id'])->update(['soft_size' => $count]); 
		}
		$url = '/api/down_content/keysugg_softsize';
		echo "<script language='javascript' 
        type='text/javascript'>";
        echo "window.location.href='$url'";
        echo "</script>";
		}else{echo 'ok!!!';}
	}

    public function test()
    {
		$result = DownContent::where('ai_json', 'LIKE', '%```%')->whereBetween('id',[1,990000])->get();
		
		foreach($result as $r){
			//var_dump($r);exit;
			$pattern = '/\{(.*?)\}/s'; // 使用s修饰符使得点号可以匹配换行符  
			$content = $r['ai_json'];
			$str = $r['ai_json'];
			if (preg_match($pattern, $str, $matches)) {
				// $matches[1] 将包含第一个匹配的大括号内的内容  
				$jsonString = $matches[0];  
				// 为了确保内容是有效的JSON，可以使用json_decode进行验证  
				$jsonData = json_decode($jsonString, true);
				if ($jsonData !== null && json_last_error() === JSON_ERROR_NONE) {  
					$content = $jsonString;
				} else {
				}
			}
			DownContent::where(['id'=>$r['id']])->update(['ai_json'=>$content]);
		}
		return Response::generateSuccess();
	}
	
}
